﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using JigLibX.Collision;
using JigLibX.Physics;
using JigLibX.Geometry;
using JigLibX.Math;
using DARE;

namespace DARE
{
    public class APhysicController : Controller, IControllerUpdate
    {

    #region fields

        protected CNode m_node = null;
        protected Body m_body = null;
        protected Vector3 m_velocity = Vector3.Zero;
        protected Vector3 m_torque = Vector3.Zero;

    #endregion

    #region ctor

        public APhysicController()
        {
            Initialize(null);
        }

        public APhysicController(CNode node)
        {
            if (node != null && node.Entity != null && node.Render3D != null && 
                node.Entity.Physic != null && node.Entity.Physic.Body != null)
                Initialize(node);
            else
                throw new Exception("A node/enity/render3d/body cannot be null in a physic controller !");
        }

        private void Initialize(CNode node)
        {
            //PhysicsSystem 
            EnableController();
            m_node = node;
            m_body = node.Entity.Physic.Body;
            m_node.Render3D.m_physicsControllers.Add(this);
            Initialize();
        }

        protected virtual void Initialize()
        { }

        public virtual void Destroy()
        { }

    #endregion

    #region properties

        public Body Body
        {
            get { return m_body; }
        }

        public CNode Node
        {
            get { return m_node; }
        }

        public Vector3 Force
        {
            get { return m_velocity; }
            set { m_velocity = value; }
        }

        public Vector3 Torque
        {
            get { return m_torque; }
            set { m_torque = value; }
        }

    #endregion

    #region methods

        public override void UpdateController(float dt)
        {
            if (m_velocity != null && m_velocity != Vector3.Zero)
            {
                m_body.AddBodyForce(m_velocity);
                if (!m_body.IsActive)
                    m_body.SetActive();
            }
            if (m_velocity != null && m_torque != Vector3.Zero)
            {
                m_body.AddBodyTorque(m_torque);
                if (!m_body.IsActive)
                    m_body.SetActive();
            }
        }

        public virtual void PreUpdate(float dt)
        { }

        public virtual void PostUpdate(float dt)
        { }

    #endregion

    }
}
